package com.training.hatton.dropboxclient.service;

import java.util.concurrent.TimeUnit;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.training.hatton.dropboxclient.content.Metadata;
import com.training.hatton.dropboxclient.content.contract.MetadataContract;
import com.training.hatton.dropboxclient.http.HttpManager;
import com.training.hatton.dropboxclient.utill.DropboxService;
import com.training.hatton.dropboxclient.utill.Signer;

public class SyncService extends IntentService{

	private static final int PERIOD = 20;
	private static final String NAME = "Dropbox Sync Service";
	private static final String URL_DELTA_BASE = "https://api.dropbox.com/1/delta";
	private static final String CURSOR = "cursor";
	private static final String HAS_MORE = "has_more";
	private static final String ENTRIES = "entries";
	private static final String RESET = "reset";
	
	private String mCursorString;
	private boolean hasMore;
	private boolean reset;
	
	public SyncService() {
		super(NAME);
	}
	@Override
	public void onCreate() {
		super.onCreate();
		mCursorString = "";
		hasMore = false;
		reset = false;
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
		while(DropboxService.isAuthorizated()){
			try{ 
				HttpPost httpPost = new HttpPost(URL_DELTA_BASE + "?cursor=" + mCursorString);
				Signer.sign(httpPost);
				String source = HttpManager.get(getApplicationContext()).performAsString(httpPost);
				manageDeltaResponceJson(source);
				if(hasMore){
					continue;
				}
				TimeUnit.SECONDS.sleep(PERIOD);
			}catch(Exception e){
				Log.d(DropboxService.TAG, "SyncError: " + e.toString());
			} 
		}
	}
	private void manageDeltaResponceJson(String source) throws Exception{
		JSONObject jsonObject = new JSONObject(source);
		mCursorString = jsonObject.getString(CURSOR);
		reset = jsonObject.getBoolean(RESET);
		if(reset){ 
			return;
		}
		hasMore = jsonObject.getBoolean(HAS_MORE);
		JSONArray jsonArray = jsonObject.getJSONArray(ENTRIES);
		if(jsonArray == null || jsonArray.length() == 0){
			return;
		}
		manageDeltaEntries(jsonArray);
	}
	private void manageDeltaEntries(JSONArray array) throws Exception{
		for (int i = 0; i < array.length(); i++) { 
			JSONArray internalArray = array.getJSONArray(i);
			String path = (String) internalArray.get(0);
			Object secondValue = null;
			if ((secondValue = internalArray.get(1)).equals(JSONObject.NULL)){
				if(getContentResolver().query(MetadataContract.MetadataColumns.CONTENT_URI, null, MetadataContract.MetadataColumns.PATH + " = ? COLLATE NOCASE", new String[]{path}, null).getCount() == 0){
					continue;
				}else{
					getContentResolver().delete(MetadataContract.MetadataColumns.CONTENT_URI, MetadataContract.MetadataColumns.PATH + " = ? COLLATE NOCASE ", new String[]{path});
				}
			}else{
				Metadata md = new Metadata((JSONObject) secondValue);
				getContentResolver().insert(MetadataContract.MetadataColumns.CONTENT_URI, Metadata.toValue(md));
			}
		}
		
	}
	public boolean hasMore(){
		return hasMore;
	}

}
